package logic

import (
	"context"
	"rpc/model/mysql"
	"rpc/model/redis"

	"rpc/internal/svc"
	"rpc/pb/cart"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	c := mysql.Goods{}

	err := c.FindGoods(in.GoodsId)
	if err != nil {
		logx.Error("商品查询失败")
		return nil, err
	}
	if c.ID == 0 {
		logx.Error("商品不存在")
		return nil, err
	}
	stock := redis.GetGoodsStock(in.GoodsId)
	if stock < in.GoodsNum {
		logx.Error("库存不足")
		return nil, err
	}

	if redis.GetExists(in.UserId, in.GoodsId) {

		if err = redis.UpdateCart(in.UserId, in.GoodsId, in.GoodsNum); err != nil {
			logx.Error("修改失败")
			return nil, err
		}
	} else {
		goodsMap := map[string]interface{}{
			"user_id":      in.UserId,
			"goods_id":     in.GoodsId,
			"num":          in.GoodsNum,
			"price":        c.GoodsPrice,
			"goods_stock":  c.GoodsStock,
			"goods_status": c.GoodsStatus,
			"goods_title":  c.GoodsTitle,
			"goods_img":    c.GoodsImg,
			"checked":      1,
		}

		if err = redis.AddCart(goodsMap); err != nil {
			logx.Error("添加错误")
			return nil, err
		}
	}

	return &cart.AddCartResponse{Success: true}, nil
}
